import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: fzykd
 * Date: 2022-04-22
 * Time: 8:48
 */
public class MyArrayList { // 顺序表
    public int[] elem;
    public int usedSize;

    public MyArrayList(){
        this.elem = new int[10];
    }

    public void create(int pos,int data) { //在指定下标放元素
        if (pos < 0 || pos > elem.length) {  // 判断pos位置的合法性
            System.out.println("pos位置不合法！"+pos+"下标插入"+data+"失败！");
            return;
        }
        if (elem.length == this.usedSize) { // 满了扩容
            elem = Arrays.copyOf(elem, elem.length * 2);
        }
        elem[pos] = data;
        usedSize++;
    }

    // 遍历顺序表
    public void display(){
        for (int i = 0; i < this.usedSize; i++) {
            System.out.print(elem[i]+" ");
        }
        System.out.println();
    }

    // 判定是否包含某个元素
    public boolean contains(int toFind) {
        for (int i = 0; i < this.usedSize; i++) {
            if (toFind == elem[i]){
                return true;
            }
        }
        return false;
    }
    // 查找某个元素对应的位置
    public int search(int toFind) {
        for (int i = 0; i < this.usedSize; i++) {
            if (toFind == elem[i]){
                return i;
            }
        }
        return -1;
    }
    // 获取 pos 位置的元素
    public int getPos(int pos) {
        if (pos < 0 || pos > elem.length){
            System.out.println("pos位置不合法！");
            return -1;
        }
        for (int i = 0; i < this.usedSize; i++) {
            if (i == pos){
                return elem[i];
            }
        }
        return -1;
    }
    // 给 pos 位置的元素设为 value
    public void setPos(int pos, int value) {
        if (pos < 0 || pos > elem.length){
            System.out.println("pos位置不合法！");
            return;
        }
        for (int i = 0; i < this.usedSize; i++) {
            if (pos == i){
                elem[i] = value;
            }
        }
    }
    //删除第一次出现的关键字key
    public void remove(int toRemove) {
        for (int i = 0; i < this.usedSize; i++) {
            if (elem[i] == toRemove){
                int j = i;
                while (j < this.usedSize-1){
                    elem[j] = elem[j+1];
                    j++;
                }
                this.usedSize--;
            }
        }
    }
    // 获取顺序表长度
    public int size() {
        return this.usedSize;
    }
    // 清空顺序表
    public void clear() {
        this.usedSize = 0;
    }
}














